<?php

namespace addons\Insurance\common\helpers;

use addons\Employees\common\models\Employees;
use Yii;
use yii\web\NotFoundHttpException;
use addons\Insurance\common\models\Insurance;
class ImportHelper
{
    public static $data = '';

    public static function Insurance($data, $cate_id=0)
    {
        ini_set('max_execution_time', '0');
        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $row=0;
            foreach ($data as $i=>$datum) {
                if (!empty($datum[0])) {
                    $employees_id = Employees::find()->where(['idcard'=>$datum[1]])->scalar();
                    $tmp = [
                        'merchant_id' =>Yii::$app->user->identity->merchant_id,
                        'employees_id' => $employees_id,
                        'pay_amount' => $datum[2],
                        'pay_time' => $datum[3],
                        'status' => 1,
                    ];
                    $model = new Insurance();
                    $model->attributes = $tmp;
//                    Yii::$app->debris->p($tmp);
                    if (!$model->save()) {
                        throw new NotFoundHttpException('第'.$i.'行导入出错，请检查数据格式');
                    }
                }
                else throw new NotFoundHttpException('导入表格数据为空，请核对');
            }

            $transaction->commit();

        } catch (\Exception $e) {
            $row+=$i;
            $transaction->rollBack();
            throw new NotFoundHttpException('第'.$row.'行导入时出错，请检查数据格式');
        }
        return true;
    }

}